import { saveFormInitialValues } from './formStorage';
import notificationService from '../../services/notificationService';
import errorHandlerService from '../../services/errorHandlerService';

type CalcFn<T> = (values: T) => Promise<any>;

export async function runFormCalculation<T = any>(form: any, storageKey: string | null, calcFn: CalcFn<T>) {
  if (!form || typeof form.validateFields !== 'function') {
    throw new Error('invalid-form');
  }

  try {
    const values = await form.validateFields();
    const res = await calcFn(values);
    // 只有在计算成功后才保存表单参数
    if (storageKey) saveFormInitialValues(storageKey, values);
    return res;
  } catch (err: any) {
    // If validation error, let the form show messages; otherwise show a generic one
    if (err && err.errorFields) {
      // validation failed - rethrow so callers can handle
      throw err;
    }
    errorHandlerService.handleCalculationError(
      err,
      '计算出错'
    );
    throw err;
  }
}